<script setup lang='ts' name="admin-role-add">
import { cloneDeep } from 'lodash-es'
import { dialogTitle } from '../types'

const title = ref('新增角色')
const visible = ref(false)
const menuOptions = ref([])
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuTreeRef = ref()

const initForm: Iform = {
    dataScope: '2',
    deptIds: [],
    menuCheckStrictly: true,
    menuIds: [],
    remark: '',
    roleId: undefined,
    roleKey: undefined,
    roleName: undefined,
    roleSort: 0,
    status: '0',
}
const formRef = ref()
const form = ref(cloneDeep(initForm))
const rules = {
    roleKey: [
        { message: '权限字符不能为空', required: true, trigger: 'blur' },
    ],
    roleName: [
        { message: '角色名称不能为空', required: true, trigger: 'blur' },
    ],
    roleSort: [
        { message: '角色顺序不能为空', required: true, trigger: 'blur' },
    ],
}
const dataScopeOptions = [
    {
        label: '全部数据权限',
        value: '1',
    },
    {
        label: '自定数据权限',
        value: '2',
    },
    {
        label: '本部门数据权限',
        value: '3',
    },
    {
        label: '本部门及以下数据权限',
        value: '4',
    },
    {
        label: '仅本人数据权限',
        value: '5',
    },
]

const statusList = [{
    label: '正常',
    value: '0',
}, {
    label: '停用',
    value: '1',
}]

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value) {
    for (let i = 0; i < menuOptions.value.length; i++) {
        menuTreeRef.value.store.nodesMap[menuOptions.value[i].id as number].expanded = value
    }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value) {
    menuTreeRef.value.setCheckedNodes(value ? menuOptions.value : [])
}
// 树权限（父子联动）
function handleCheckedTreeConnect(value) {
    form.value.menuCheckStrictly = !!value
}

// 所有菜单节点数据
function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    // 半选中的菜单节点
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
    return checkedKeys
}

// 打开弹窗
async function showDialog(type, row) {
    menuNodeAll.value = false
    title.value = type
    const { dataScope, roleId, roleKey, roleName, roleSort, status } = row
    switch (type) {
        case dialogTitle.ADD :
            form.value = cloneDeep(initForm)
            // const res = await getAddRoleTreeData()
            // menuOptions.value = res
            visible.value = true
            break
        case dialogTitle.EDIT :
            form.value = {
                menuCheckStrictly: true,
                menuIds: [],
                remark: '',
                roleId,
                roleKey,
                roleName,
                roleSort,
                status,
            }
            const menuTreeData = await getEditRoleTreeData(row.roleId)
            menuOptions.value = menuTreeData.menus
            form.value.menuIds = menuTreeData.checkedKeys
            visible.value = true
            nextTick(() => {
                menuTreeData.checkedKeys.forEach((v) => {
                    menuTreeRef.value.setChecked(v, true, false)
                })
            })
            break
        case dialogTitle.CONFIG_PERMISSION :
            form.value = {
                dataScope,
                deptIds: [],
                menuCheckStrictly: true,
                roleId,
                roleKey,
                roleName,
            }
            const deptTreeData = await getRoleDeptTree(roleId)
            menuOptions.value = deptTreeData.depts
            form.value.deptIds = deptTreeData.checkedKeys
            visible.value = true
            nextTick(() => {
                deptTreeData.checkedKeys.forEach((v) => {
                    menuTreeRef.value.setChecked(v, true, false)
                })
            })
            break
    }
}

// 取消按钮
function cancel() {
    visible.value = false
}

// 提交按钮
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    formEl.validate((valid) => {
        if (valid) {
            const { dataScope, remark, roleId, roleKey, roleName, roleSort, status } = form.value
            const params = {
                menuIds: undefined,
                remark,
                roleId,
                roleKey,
                roleName,
                roleSort,
                status,
                deptIds: undefined,
            }
            switch (title.value) {
                case dialogTitle.ADD :
                    params.menuIds = getMenuAllCheckedKeys()
                    addRole(params).then(() => {
                        getListData()
                        ElMessage.success('新增成功')
                    })
                    break
                case dialogTitle.EDIT :
                    params.menuIds = getMenuAllCheckedKeys()
                    editRole(params).then(() => {
                        getListData()
                        ElMessage.success('修改成功')
                    })
                    break
                case dialogTitle.CONFIG_PERMISSION :
                    if (dataScope === '2')
                        params.deptIds = getMenuAllCheckedKeys()
                    updateRoleDataScope({
                        dataScope,
                        deptIds: params.deptIds,
                        roleId,
                        roleKey,
                        roleName,
                    }).then(() => {
                        getListData()
                        ElMessage.success('分配成功')
                    })
                    break
            }
            visible.value = false
        }
    })
}
</script>

<template>
    <el-dialog v-model="visible"
               :title="title"
               width="666px"
    >
        <el-form ref="formRef"
                 class="dialog-form"
                 :model="form"
                 :rules="rules"
                 label-width="100px"
                 label-position="right"
        >
            <el-form-item label="角色名称"
                          prop="roleName"
            >
                <el-input v-model="form.roleName"
                          :disabled="title === dialogTitle.CONFIG_PERMISSION"
                          placeholder="请输入角色名称"
                />
            </el-form-item>

            <el-form-item v-if="title !== dialogTitle.CONFIG_PERMISSION"
                          label="状态"
            >
                <el-radio-group v-model="form.status">
                    <el-radio v-for="dict in statusList"
                              :key="dict.value"
                              :value="dict.value"
                    >
                        {{ dict.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item v-if="title === dialogTitle.CONFIG_PERMISSION"
                          label="权限范围"
            >
                <el-select v-model="form.dataScope">
                    <el-option v-for="item in dataScopeOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="分配区域">
                <el-select v-model="form.dataScope">
                    <el-option v-for="item in dataScopeOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="所属应用">
                <el-select v-model="form.dataScope">
                    <el-option v-for="item in dataScopeOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item v-show="title !== dialogTitle.CONFIG_PERMISSION || (title === dialogTitle.CONFIG_PERMISSION && !['1', '3', '4', '5'].includes(String(form.dataScope)))"

                          label="菜单权限"
            >
                <el-checkbox v-model="menuExpand"
                             @change="handleCheckedTreeExpand"
                >
                    展开/折叠
                </el-checkbox>

                <el-checkbox v-model="menuNodeAll"
                             @change="handleCheckedTreeNodeAll"
                >
                    全选/全不选
                </el-checkbox>

                <el-checkbox v-model="form.menuCheckStrictly"
                             @change="handleCheckedTreeConnect"
                >
                    父子联动
                </el-checkbox>
            </el-form-item>

            <el-form-item v-show="title !== dialogTitle.CONFIG_PERMISSION || (title === dialogTitle.CONFIG_PERMISSION && !['1', '3', '4', '5'].includes(String(form.dataScope)))"
                          label=""
            >
                <el-tree ref="menuTreeRef"
                         class="tree-border"
                         :data="menuOptions"
                         show-checkbox
                         node-key="id"
                         :check-strictly="!form.menuCheckStrictly"
                         :props="{
                             children: 'children',
                             label: 'label',
                         }"
                />
            </el-form-item>

            <el-form-item v-if="title !== dialogTitle.CONFIG_PERMISSION"
                          label="备注"
            >
                <el-input v-model="form.remark"
                          type="textarea"
                          placeholder="请输入内容"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary"
                           @click="submitForm(formRef)"
                >
                    确 定
                </el-button>

                <el-button @click="cancel">
                    取 消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
